package com.woniu.gf.pawn.productentityweb.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.woniu.gf.pawn.management.client.ManagementClient;
import com.woniu.gf.pawn.client.ProductClient;
import com.woniu.gf.pawn.comm.core.domain.Management;
import com.woniu.gf.pawn.comm.core.domain.ProductBigType;
import com.woniu.gf.pawn.comm.core.domain.ProductPropertyValue;
import com.woniu.gf.pawn.comm.core.domain.ProductSmallType;
import com.woniu.gf.pawn.comm.core.dto.ResultDto;
import com.woniu.gf.pawn.comm.core.util.OssUntil;
import com.woniu.gf.pawn.dto.*;
import com.woniu.gf.pawn.management.client.ManagementClient;
import com.woniu.gf.pawn.management.param.SelectManagementByRoleIdParam;
import com.woniu.gf.pawn.param.PageParam;
import com.woniu.gf.pawn.param.ProductEntityParam;

import com.woniu.gf.pawn.productentityweb.service.IProductEntityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author TL
 * @since 2020-10-14
 */
@RestController
@RequestMapping("/product-entity")
@Slf4j
@Api(tags = "商品实体")
public class ProductEntityController {

    @Autowired
    private IProductEntityService productEntityService;
    @Autowired
    private ManagementClient managerClient;
    @Autowired
    private ProductClient productClient;

    /**
     * 商品查询（状态（待鉴定，待评估，已评估）、操作人、模糊条件（商品名称、分类名称）、录入日期）
     * @param pageDto
     * @return
     */
    @GetMapping("findProduct")
    @ApiOperation("商品查询")
    public ResultDto findProduct(PageDto pageDto){
        log.info("参数-{}",pageDto);

        if (pageDto.getPageIdx() == null) {
            pageDto.setPageIdx(1);
        }
        if (pageDto.getPageSize() == null) {
            pageDto.setPageSize(10);
        }
        PageParam pageParam = new PageParam();
        BeanUtils.copyProperties(pageDto,pageParam);
        if (StringUtils.isNotEmpty(pageDto.getQuery())) {
            ProductSmallType smallType= productEntityService.findSmallTypeName(pageDto.getQuery());
            ProductBigType bigType= productEntityService.findBigTypeName(pageDto.getQuery());
            if (smallType != null) {
                pageParam.setSmallTypeId(smallType.getProductSmallTypeId());
            }else if (bigType != null) {
                pageParam.setBigTypeId(bigType.getProductBigTypeId());
            }else{
                pageParam.setProductEntityName(pageDto.getQuery());
            }
        }
        if (StringUtils.isNotEmpty(pageDto.getManageName())) {
            Management management=productEntityService.findManagerId(pageDto.getManageName());
            pageParam.setManagerId(management.getManagementId());
        }
        IPage<ProductEntityDto> productBigTypeIPage = productEntityService.findPageProduct(pageParam);

        return ResultDto.success(200,"查询成功",productBigTypeIPage);
    }

    /**
     * 根据ID查询商品
     * @param productEntityId
     * @return
     */
    @GetMapping("findOneProductEntity/{productEntityId}")
    @ApiOperation("根据ID查询商品")
    public ResultDto findOneShopInfo(@PathVariable("productEntityId") Integer productEntityId){
        log.info("参数-{}",productEntityId);
        ProductEntityDto productEntityDto= productEntityService.findOneShopInfo(productEntityId);
        List<ProductImageDto> productImageDtos = productEntityService.findImages(productEntityId);
        productEntityDto.setProductImageDtos(productImageDtos);
        if (productEntityDto == null) {
            return ResultDto.fail(404,"商品不存在");
        }
        String centers = productEntityDto.getProductPropertyCenters();
        System.out.println(centers);
        if (centers.contains(",")) {
            List<ProductPropertyDto> propertyDtos = new ArrayList<>();
            List<ProductPropertyValue> propertyValues = new ArrayList<>();
            String[] split = centers.split(",");
            List<Integer> centreIds = new ArrayList<>();
            int id=0;
            for (int i = 0; i < split.length; i++) {
                    centreIds.add(Integer.parseInt(split[i]));
            }
            for (Integer centreId : centreIds) {
                int newId=id;
                ProductPropertyAndValueDto propertyAndValueDto= productEntityService.findPropertyAndValues(centreId);
                id=propertyAndValueDto.getProductPropertyId();
                System.out.println(propertyAndValueDto.toString());
                ProductPropertyValue productPropertyValue = new ProductPropertyValue();
                BeanUtils.copyProperties(propertyAndValueDto,productPropertyValue);
                if (id!=newId) {
                    propertyValues = new ArrayList<>();

                }
                propertyValues.add(productPropertyValue);
                ProductPropertyDto propertyDto = new ProductPropertyDto();
                BeanUtils.copyProperties(propertyAndValueDto,propertyDto);
                propertyDto.setProductPropertyValues(propertyValues);
                propertyDtos.add(propertyDto);
            }

            productEntityDto.setProductPropertyDto(propertyDtos);
            for (int i = 0; i < productEntityDto.getProductPropertyDto().size()-1; i++) {
                if (productEntityDto.getProductPropertyDto().get(i).getProductPropertyId()==productEntityDto.getProductPropertyDto().get(i+1).getProductPropertyId()) {
                    productEntityDto.getProductPropertyDto().remove(i);
                }
            }
        }
        return ResultDto.success(200,"查询成功",productEntityDto);
    }

    /**
     * 添加商品
     * @param productEntityDto
     * @return
     */
    @PostMapping("addProductEntity")
    @Transactional
    @ApiOperation("添加商品")
    public ResultDto findProduct(@RequestBody @Valid AddProductEntityDto productEntityDto){
        ProductEntityParam productEntityParam = new ProductEntityParam();
        BeanUtils.copyProperties(productEntityDto,productEntityParam);
        productEntityService.addProductEntity(productEntityParam);
        return ResultDto.success(200,"新增成功");
    }

    /**
     * 修改商品
     * @param productEntityDto
     * @return
     */
    @PostMapping("updateProductEntity")
    @Transactional
    @ApiOperation("修改商品")
    public ResultDto updateProductEntity(@RequestBody @Valid ProductEntityDto productEntityDto){
        ProductEntityParam productEntityParam = new ProductEntityParam();
        BeanUtils.copyProperties(productEntityDto,productEntityParam);
        productEntityService.updateProductEntity(productEntityParam);
        return ResultDto.success(200,"修改成功");
    }

    /**
     * 删除商品
     * @param productEntityId
     * @return
     */
    @GetMapping("deleteProduct/{productEntityId}")
    @ApiOperation("删除商品")
    public ResultDto deleteProduct(@PathVariable("productEntityId") Integer productEntityId){
        productEntityService.deleteProductById(productEntityId);
        return ResultDto.success(200,"删除成功");
    }

    /**
     * 上传图片
     * @param files
     * @return
     */
    @PostMapping("upLoad")
    @ApiOperation("上传图片")
    public ResultDto upLoad(List<MultipartFile> files){
        List<String> strings = OssUntil.putObject(files);
        return ResultDto.success(200,"上传成功",strings);
    }
    /**
     * 根据角色id查询拥有该角色的管理员集合
     */

    @ApiOperation("根据角色id查询拥有该角色的管理员集合")
    @GetMapping("/selectManagementByRoleId")
    public ResultDto selectManagementByRoleId(@RequestParam("roleId") Integer roleId){
        SelectManagementByRoleIdParam roleIdParam = new SelectManagementByRoleIdParam();
        roleIdParam.setRoleId(roleId);
        ResultDto resultDto = managerClient.selectManagementByRoleId(roleIdParam);
        return resultDto;
    }
    /**
     * 根据选择的商品大类获取所需鉴定图类型集合，商品小类集合，品牌集合，属性类型下属性及值集合
     * @param bigTypeId
     * @return
     */
    @GetMapping("findAllByBigTypeId/{bigTypeId}")
    @ApiOperation("根据选择的商品大类获取所需鉴定图类型集合，商品小类集合，品牌集合，属性类型下属性及值集合")
    public ResultDto findAllByBigTypeId(@PathVariable("bigTypeId")Integer bigTypeId){
        return productClient.findAllByBigTypeId(bigTypeId);
    }
    /**
     * 查询所有大类
     */
    @GetMapping("findAllBigType")
    @ApiOperation("查询所有大类")
    public ResultDto findAllBigType(){
        return productClient.findAllBigType();
    }
}

